package com.yanhao.viewmode

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.yanhao.etx.error
import com.yanhao.repository.UserInfoRepository
import com.yanhao.utils.MMKVUtils
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

class LoginViewModel(private val resp: UserInfoRepository) : BaseViewModel() {

    fun login(username: String, password: String) {
        viewModelScope.launch {
            resp.logint(username, password).catch { e: Throwable ->
                errorCatch(e)
            }.onStart {
                _loadding.value = true
            }.collect {
                _loadding.value = false
                if (it.errorCode == 0) {
                    val data = it.data
                    MMKVUtils.saveUserInfo(data)
                    //设置用户数据到全局livedata中
                    UserInfoLivedata.getInstance().postData(data)
                } else {
                    _errorMsg.value = it.errorMsg
                }
            }
        }
    }

}

class LoginViewModelFactory : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(LoginViewModel::class.java)) {
            return LoginViewModel(resp = UserInfoRepository()) as T
        }
        throw IllegalArgumentException("不能找到 LoginViewModelFactory")
    }

}